package cc.rengu.igas.route.core.service.trans;

import cc.rengu.igas.route.common.constant.SmartRouteParamConstant;
import cc.rengu.igas.route.common.dao.MultiDyncDataStaticMapper;
import cc.rengu.igas.route.common.dao.impl.MultiDyncDataStaticMapperImpl;
import cc.rengu.igas.route.common.entity.MultiDyncDataStatic;
import cc.rengu.igas.route.core.model.MultiDyncDataRuleGroup;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.utility.base.StringUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.util.ArrayList;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 多路比例路由动态统计数据落地
 *
 * @author xlz
 * @version 1.0
 * @date 20200428
 */
public class SchuTransMultiRouterDataSave extends RadpService {
    private RgLogger rgLog = RgLog.getLogger(this.getClass().getName());

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {
        //保存多路比例路由数据到数据库
        ConcurrentHashMap<String, Object> concurrentHashMap = null;
        MultiDyncDataStaticMapper multiDyncDataStaticMapper = null;
        try {
            multiDyncDataStaticMapper = new MultiDyncDataStaticMapperImpl();
            concurrentHashMap = UnifiedCache.list(SmartRouteParamConstant.ROUTE_DATA_MULTI);
        } catch (Exception e) {
            rgLog.debug("系统缓存取数据出错！");
        }
        if (!Optional.ofNullable(concurrentHashMap).isPresent()) {
            rgLog.debug("系统缓存中未找到比例路由缓存数据，无需落地");
            reset();
            return 0;
        }
        for (ConcurrentHashMap.Entry<String, Object> map : concurrentHashMap.entrySet()) {
            MultiDyncDataRuleGroup dyncDataRuleGroup = (MultiDyncDataRuleGroup) map.getValue();
            ArrayList<MultiDyncDataStatic> multiDyncDataStatics = dyncDataRuleGroup.getMultiDyncDataRuleArrayList();
            if (null == multiDyncDataStatics || multiDyncDataStatics.isEmpty()) {
                continue;
            }
            try {
                multiDyncDataStaticMapper.setMultiDyncDataUsedByPk(dyncDataRuleGroup.getMultiDyncDataRuleArrayList());
            } catch (Exception e) {
                rglog.debug("记录比例路由动态统计数据表失败<{}>,内存缓存key为<{}>!", StringUtil.ExceptionToString(e), map.getKey());
            }
        }
        //add by lizhangtao 20200603 每次调用完成时重置
        reset();
        return 0;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }
}
